package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    //口味表service mp实现类
    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    //自定异常和事物管理有什么区别呢
    @Transactional
    public void saveDishAndFlavor(DishDto dishDto) {
        //保存菜品的基本信息
        //dishDto有菜品的基本信息,其他信息没有匹配字段.添加不了
        save(dishDto);
        log.info("[保存菜品信息和菜品风味信息]");
        //获取多个口味信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        //判断口味信息是否有值
        if (flavors!=null&&flavors.size()>0) {
            //因为口味表需要菜品表的id,一个菜品的多个口味
            //遍历口味,赋值菜品id
            for (final DishFlavor flavor : flavors) {
                flavor.setDishId(dishDto.getId());
            }
        }
        //批量添加
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getDishAndFlavor(Long id) {
        log.info("id{}",id);
        DishDto dishDto = new DishDto();
        Dish byId = getById(id);
        //将byid对象中的属性copy到dishDto对象中
        BeanUtils.copyProperties(byId,dishDto);
        //拼接sql语句
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> list = dishFlavorService.list(lambdaQueryWrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    @Transactional
    public void updateDishAndDishFlavor(DishDto dishDto) {
        updateById(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();
        if (flavors!=null&&flavors.size()>0){
            for (final DishFlavor flavor : flavors) {
                flavor.setDishId(dishDto.getId());
            }
        }

        dishFlavorService.saveBatch(flavors);

    }
}
